package com.ruoyi.aitcommon.service;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.ruoyi.aitcommon.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.config.ConfigManager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;

/**
 * 邮件发送服务
 * 封装hutool
 * @author Administrator
 *
 */
@Service
public class MailService {
	@Autowired
	EntityCache entityCache;
	@Autowired
	IAitEntityInfoService infoService;
	@Autowired
	ConfigManager configManager;
	
	public void send(Map<String,Object> props,List<Map<String,Object>> datas,String filePath,Map<String, Object> entityInfo) throws Exception {
//		从缓存过滤重复数据
		List<Map<String, Object>> filterlist = entityCache.filterEntityChange(entityInfo, datas);
		for (Map<String, Object> data : filterlist) {
			try{
				final String ret = restInvoke(props, data,filePath);
				infoService.insertAitEntityInfo(entityInfo, data, null);
			}catch (Exception ex){
				infoService.insertAitEntityInfo(entityInfo, data, ex);
			}
		}
	}

	private String restInvoke(Map<String, Object> props, Map<String, Object> data,String filePath) throws Exception {
//		用data数据覆盖props设置
		props.putAll(data);
//		创建发送邮箱信息
		Map<String,Object> from = (Map<String,Object>)props.get("from");
		MailAccount account = new MailAccount();
		account.setHost(from.get("host").toString());
		account.setPort(Integer.valueOf(from.get("port").toString()));
		account.setAuth(Boolean.valueOf(from.get("auth").toString()));
		account.setFrom(from.get("from").toString());
		account.setUser(from.get("user").toString());
		account.setPass(from.get("pass").toString());
		account.setSslEnable(Boolean.valueOf(from.get("sslEnable").toString()));
//		读取邮件模板
		String htmltemp = configManager.loadConfigFileStr(props.get("filePath").toString());
//		邮件附件
		File attfile=null;
		if(StrUtil.isNotBlank(filePath))
			attfile = new File(filePath);
//		实例化模板,将变量->模板中
		String html = StrUtil.format(htmltemp, data);
//		获取其他参数
		String title= props.get("title").toString();
		List<String> tos=(List<String>) props.get("tos");
		if(ObjUtils.isBlank(tos)){
			throw new Exception("邮件tos为空!");
		}
//		发送邮件
		String ret="";
		if(ObjUtils.isNotBlank(attfile))
			ret = MailUtil.send(account, tos, title, html, true, attfile);
		else
			ret=MailUtil.send(account,tos,title, html,true);
		System.out.println(ret);
		return ret;
	}
}
